import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  LoggerService,
} from '@nestjs/common';
import { FastifyReply } from 'fastify';
import * as moment from 'moment';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: LoggerService) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;
    const { message, code } = exception.getResponse() as FastifyReply & {
      message: string;
    };
    let res = {
      code: code || status,
      timestamp: moment().format('yyyy-MM-DD HH:mm:ss'),
      path: request.url,
      error: 'Bad Request',
      message,
    };
    this.logger.error(message, {
      request: `${request.method} ${request.protocol}://${request.ip}${request.url}`,
      query: request.query,
      params: request.params,
      body: request.body,
      response: res,
      stack: exception.stack,
    });
    response.code(status).send(res);
  }
}
